package tq.com.upload;

import android.os.AsyncTask;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

public class TQUploadFileTask extends AsyncTask<String, Long, Integer> {
    private TQUploadFileManager.Build mBuild;
    private OkHttpClient mOkHttpClient;
    private String fileId;

    private Call mCall;
    public TQUploadFileTask(TQUploadFileManager.Build pBuild){
        mBuild = pBuild;
    }
    @Override
    protected Integer doInBackground(String... pStrings) {
        mOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .build();

        try {
            Request.Builder lBuilder = new Request.Builder()
                    .url(mBuild.getUrl());
            if(mBuild.getToken() != null){
                lBuilder.addHeader("X-Auth-Token", mBuild.getToken());
            }


            File lFile = new File(mBuild.getFile());
            String type = getExtensionName(lFile.getName());

            MediaType lMediaType = MediaType.parse("application/octet-stream");
            MultipartBody.Builder lBuilder1 = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file_type", type)
                    .addFormDataPart("file", lFile.getName(), RequestBody.create(lMediaType, lFile));
             RequestBody lRequestBody = lBuilder1.build();

            lBuilder.post(new RequestProgressBody(lRequestBody));
            mCall = mOkHttpClient.newCall(lBuilder.build());
            Response lResponse = mCall.execute();

            if(lResponse.code() == 200){
                JSONObject lObject = new JSONObject(lResponse.body().string());
                int ret = lObject.optInt("ret");
                if(ret == 0){
                    fileId = lObject.optString("fid");
                }
            }else{
                lResponse.body().toString();
                return 1;
            }

        }catch (Exception pE){
            pE.printStackTrace();
            return 1;
        }
        return 0;
    }

    @Override
    protected void onProgressUpdate(Long... values) {
        super.onProgressUpdate(values);
        if(values.length >= 2 && mBuild.getUploadFileListener() != null){
            mBuild.getUploadFileListener().process(values[0], values[1]);
        }
    }

    @Override
    protected void onPostExecute(Integer pI) {
        super.onPostExecute(pI);

        if(mBuild.getUploadFileListener() == null) return;

        if(pI == 0){
            mBuild.getUploadFileListener().success(fileId);
        }else {
            mBuild.getUploadFileListener().fail("文件上传失败");
        }
    }


    @Override
    protected void onCancelled(Integer pInteger) {
        super.onCancelled(pInteger);

        mCall.cancel();
    }

    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    public class RequestProgressBody extends RequestBody {
        private final RequestBody requestBody;
        private BufferedSink bufferedSink;

        public RequestProgressBody(RequestBody requestBody) {
            this.requestBody = requestBody;
        }

        public MediaType contentType() {
            return requestBody.contentType();
        }

        @Override
        public long contentLength() throws IOException {
            return requestBody.contentLength();
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            if (bufferedSink == null) {
                bufferedSink = Okio.buffer(sink(sink));
            }
            requestBody.writeTo(bufferedSink);
            bufferedSink.flush();
        }

        private Sink sink(Sink sink) {
            return new ForwardingSink(sink) {
                long bytesWritten = 0L;
                long contentLength = 0L;

                @Override
                public void write(Buffer source, long byteCount) throws IOException {
                    super.write(source, byteCount);
                    if (contentLength == 0) {
                        contentLength = contentLength();
                    }
                    bytesWritten += byteCount;

                    if(mBuild.getUploadFileListener() != null){
                        publishProgress(bytesWritten, contentLength);
                    }
//                    if (uploadProgressHandler != null) {
//                        uploadProgressHandler.obtainMessage(ANConstants.UPDATE,
//                                new Progress(bytesWritten, contentLength)).sendToTarget();
//                    }
                }
            };
        }
    }
}
